﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Telerik.Sitefinity.GenericContent.Model;
using Telerik.Sitefinity.Modules.Lists;
using Telerik.Sitefinity.Lists.Model;
using Telerik.Sitefinity.Workflow;

namespace Migration.Classes
{
	public static class MigrationLists
	{
		private static ListsManager m_ListsManager;

		static MigrationLists()
		{
			m_ListsManager = ListsManager.GetManager(MigrationSettings.ListsProvider);
		}

		private static void CheckManagers()
		{
			if (m_ListsManager.Provider == null || MigrationSettings.ApplicationRestarted)
			{
				m_ListsManager = ListsManager.GetManager(MigrationSettings.ListsProvider);
			}
		}

		public static void ImportList(Telerik.Sitefinity.Services.Migration.MigrationList listContent)
		{
			CheckManagers();

			var id = listContent.Id;

			var checkList = m_ListsManager.GetLists().Where(l => l.Id == id).SingleOrDefault();
			if (checkList != null)
			{
				MigrationLogger.AppendLogMessage(String.Format("Skipping list \"<b>{0}</b>\", already exists.", checkList.Title));
				MigrationLogger.AppendNewLine();
				return;
			}

			var newList = m_ListsManager.CreateList(id);

			newList.Title = listContent.Name;
			newList.Owner = MigrationUsers.DefaultOwner;
			newList.DateCreated = listContent.Created;
			newList.UrlName = MigrationUtils.GetUrlName(listContent.Name);

			m_ListsManager.SaveChanges();

			foreach (var listItem in listContent.Items)
			{
				var listItemId = listItem.Id;
				var newListItem = m_ListsManager.CreateListItem(listItemId);
				newListItem.Title = listItem.Headline;
				newListItem.Content = listItem.Content;
				newListItem.Parent = newList;
				newListItem.UrlName = MigrationUtils.GetUrlName(listItem.Headline);
				newList.ListItems.Add(newListItem);

				var masterId = newListItem.OriginalContentId;

				if (newListItem.Status == ContentLifecycleStatus.Master)
				{
					m_ListsManager.CheckOut(newListItem);
					masterId = newListItem.Id;
				}

				//m_ListsManager.RecompileItemUrls<ListItem>(newListItem);
				m_ListsManager.SaveChanges();

				var contextBag = new Dictionary<string, string>();
				contextBag.Add("ContentType", newListItem.GetType().FullName);

				WorkflowManager.MessageWorkflow(
					masterId,
					newListItem.GetType(),
					MigrationSettings.GenericContentProvider,
					"Publish",
					false,
					contextBag);
			}

			MigrationLogger.AppendLogMessage(String.Format("Imported list \"<b>{0}</b>\" with <b>{1}</b> item(s).", newList.Title, listContent.Items.Count));
			MigrationLogger.AppendNewLine();
		}
	}
}
